from web.forms.BootStrapForms import BootStrapModelForm
from web import models
from django import forms
from django.core.exceptions import ValidationError
from web.forms.widgets import ColorRadioSelect


class ProjectAdd(BootStrapModelForm):
    BootStrap_exclude = ['color']

    # 修改desc的Html样式 方式1 直接重写字段
    # desc = forms.CharField(widget=forms.Textarea(attrs={'xxx': 123}))
    class Meta:
        model = models.Project
        fields = ['name', 'color', 'desc']
        widgets = {
            # 修改desc的Html样式 方式2 修改widgets插件样式
            'desc': forms.Textarea,  # forms.Textarea 后面的括号可以不写，源码中会补全括号
            'color': ColorRadioSelect(attrs={'class': 'color-radio'}),
        }

    # 重写构造函数，将request传入对象中
    def __init__(self, request, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.request = request

    def clean_name(self):
        name = self.cleaned_data['name']
        # 钩子函数对表单数据进行校验
        # 1.校验当前操作者是否超过最大项目数量限制
        project_max = self.request.tracer.price_policy.project_num
        count = models.Project.objects.filter(creator=self.request.tracer.user).count()
        if count >= project_max:
            raise ValidationError('项目创建数量已超过限制，请购买套餐！')
        # 2.校验当前用户创建的项目是否重名
        exist = models.Project.objects.filter(name=name, creator=self.request.tracer.user).exists()
        if exist:
            raise ValidationError('项目名称已存在，请修改后提交！')
        return name
